package com.cebbank.yyi.springbootapp.jingtang.test;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.cebbank.yyi.springbootapp.jingtang.dao.RcDocDao;
import com.cebbank.yyi.springbootapp.jingtang.dao.RcDocRecordsDao;
import com.cebbank.yyi.springbootapp.jingtang.dto.AttachmentFileDto;
import com.cebbank.yyi.springbootapp.jingtang.dto.ConditionParams;
import com.cebbank.yyi.springbootapp.jingtang.dto.FileOperatorParams;
import com.cebbank.yyi.springbootapp.jingtang.entity.DownloadFileInfo;
import com.cebbank.yyi.springbootapp.jingtang.entity.RcDoc;
import com.cebbank.yyi.springbootapp.jingtang.entity.RcDocRecords;
import com.cebbank.yyi.springbootapp.jingtang.utils.FileUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Slf4j
public class ApplyMappingService2 {

    @Autowired
    private RcDocRecordsDao rcDocRecordsDao;

    @Autowired
    private RcDocDao rcDocDao;

    public ResponseDTO2 applyMapping(String json, String token, ConditionParams conditionParams) throws Exception {
        Gson gson = new Gson();
        ResponseDTO2 testBean = gson.fromJson(json, ResponseDTO2.class);
        if (testBean.getData() == null) {
            log.error("获取的data域为null-{}", conditionParams);
            return null;
        }

        List<ResponseDTO2.DataDTO.PageDTO.RecordsDTO> records = testBean.getData().getPage().getRecords();
        for (ResponseDTO2.DataDTO.PageDTO.RecordsDTO record : records) {

            String rawId = String.valueOf(record.getId());
            String id = record.getId() + FileUtil.getVersion();
            RcDocRecords existRecords = rcDocRecordsDao.selectById(id);
            if (null != existRecords) {
                continue;
            }
            String doc_id = record.getRulesId();
            String doc_id_Z = doc_id + "Z";
            String new_doc_id;
            List<RcDoc> rcDocs = rcDocDao.selectOrderByUpdateTm(doc_id_Z);
            if (CollUtil.isEmpty(rcDocs)) {
                log.error("{} 未查询到原文件记录，默认用Z5结尾进行同步", id);
                new_doc_id = doc_id + "Z5";
            } else {
                new_doc_id = rcDocs.get(0).getId();
            }
            String act_form_name = record.getFileName();
            String act_form_code = record.getFileNo();
            String create_time = record.getEffectDate();
            String update_time = record.getUpdDate();
            String creator = "";
            String modifier = "";
            String preparedUserInfo = record.getPreparedUserInfo();
            if (StrUtil.isNotEmpty(preparedUserInfo)) {
                Type type = new TypeToken<List<IssUserInfo>>() {
                }.getType();
                List<IssUserInfo> prepares = gson.fromJson(preparedUserInfo, type);
                for (IssUserInfo userInfo : prepares) {
                    if (userInfo.getUserNo() == null) {
                        System.err.println("当前prepares用户的UserNo为null, 已经跳过。" + userInfo);
                        break;
                    } else {
                        creator = userInfo.getUserNo();
                        modifier = creator;
                    }

                }
            }
            String act_form_version = record.getFileVersion();
            String act_form_year = record.getSecrecyTerm();
            String act_form_type = record.getMediumStr().equals("纸质") ? "PAPER" : "E_BOOK";
            RcDocRecords rcDocRecords = new RcDocRecords();
            rcDocRecords.setId(id);
            rcDocRecords.setActFormName(act_form_name);
            rcDocRecords.setActFormCode(act_form_code);
            rcDocRecords.setCreateTime(create_time);
            rcDocRecords.setUpdateTime(update_time);
            rcDocRecords.setCreator(creator);
            rcDocRecords.setModifier(modifier);
            rcDocRecords.setDeleteFlag("0");
            String regex = "\\d+"; // 匹配一个或多个数字
            if(StrUtil.isNotEmpty(act_form_version)) {
                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher(act_form_version);
                if (matcher.find()) {
                    rcDocRecords.setActFormVersion(matcher.group());
                } else {
                    log.error("{}，未匹配到版本号", id);
                }
            }
            rcDocRecords.setActFormType(act_form_type);
//            new_doc_id ="";
            rcDocRecords.setDocId(new_doc_id);
            rcDocRecords.setActFormYear(act_form_year);
            rcDocRecords.setSaveType("1");
//                rcDocRecords.setSaveType(record.getMediumStr());
            String filePath = record.getFilePath();
            if (StrUtil.isNotEmpty(filePath)) {
                DownloadFileInfo fileDownloadInfo = new DownloadFileInfo();
                fileDownloadInfo.setFilePath(filePath);
                fileDownloadInfo.setFileName(record.getFileName() + ".docx");
                String downLoadFileName = FileUtil.downloadFile(token, fileDownloadInfo, rawId);
                FileOperatorParams fileOperatorParams = new FileOperatorParams();
                fileOperatorParams.setDocId(new_doc_id);
                fileOperatorParams.setDocName(downLoadFileName);
                String uploadResponseStr = FileUtil.uploadAttachmentFile2(fileOperatorParams, rawId);
                if (StrUtil.isNotEmpty(uploadResponseStr)) {
                    AttachmentFileDto attachmentFileDto = gson.fromJson(uploadResponseStr, AttachmentFileDto.class);
                    String attachmentName = attachmentFileDto.getAttachmentName();
                    String attachmentUrl = attachmentFileDto.getAttachmentUrl();
                    if (attachmentName.endsWith(".pdf")) {
                        rcDocRecords.setMainFileName(attachmentName);
                        rcDocRecords.setMainFileUrl(attachmentUrl);
                    } else {
                        rcDocRecords.setMinorFileName(attachmentName);
                        rcDocRecords.setMinorFileUrl(attachmentUrl);
                    }
                }
            }
            try {
                rcDocRecordsDao.insert(rcDocRecords);
            } catch (Exception e) {
                log.error("{}导入失败", id, e);
            }
        }

        return testBean;
    }
}
